package com.woorigil.social.controller.member;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthConsumer;
import oauth.signpost.basic.DefaultOAuthProvider;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.woorigil.social.controller.BaseController;
import com.woorigil.social.domain.member.MemberDao;

@Controller
public class OAuthController extends BaseController {
	@Autowired MemberDao memberDao;
	String consumerKey = "3CBMaCxqOWfd";
	String consumerSecret = "505B92EBCGI_wEh6utmc";
	String naver2_requestTokenUrl = "https://nid.naver.com/naver.oauth?mode=req_req_token";
	String naver2_accessTokenUrl = "https://nid.naver.com/naver.oauth?mode=req_acc_token";
	String naver2_authorizeUrl = "https://nid.naver.com/naver.oauth?mode=auth_req_token";
	OAuthConsumer consumer;
	OAuthProvider provider;
	String token;
	String secret;
	
	@RequestMapping("oauth/loginForm")
	public ModelAndView loginForm() throws Exception {
		System.setProperty("debug", "true");
		// oauth : get request token
		consumer = new DefaultOAuthConsumer(consumerKey, consumerSecret);
		provider = new DefaultOAuthProvider(naver2_requestTokenUrl, naver2_accessTokenUrl, naver2_authorizeUrl);
		String oauthLoginFormUrl = provider.retrieveRequestToken(consumer, "http://oauth/callback.html");
		token = consumer.getToken();
		secret = consumer.getTokenSecret();
//		oAuthUser.setRequestToken(consumer.getToken());
//		oAuthUser.setRequestTokenSecret(consumer.getTokenSecret());
		
		return new ModelAndView(new RedirectView(oauthLoginFormUrl));
	}
	
	@RequestMapping("oauth/callback")
	public ModelAndView callback(@RequestParam("oauth_token") String oauthToken, @RequestParam("oauth_verifier") String oauthVerifier, String userid) throws Exception {
		System.setProperty("debug", "true");
		//oauth : get access token
		consumer.setTokenWithSecret(token, secret);
		provider.setOAuth10a(true);
		provider.retrieveAccessToken(consumer, oauthVerifier);
		
		System.out.println("oauthToken : " + oauthToken);
		System.out.println("oauthVerifier : " + oauthVerifier);
		System.out.println("userid : " + userid);
		ModelAndView mav = new ModelAndView(getForwordPage("oauth/success"));
		return mav;
	}
}
